#!/bin/sh
set -e # exit on error

###
# #%L
# **********************************************************************
# ORGANIZATION  :  Pi4J
# PROJECT       :  Pi4J :: Java Examples
# FILENAME      :  build
#
# This file is part of the Pi4J project. More information about
# this project can be found here:  https://pi4j.com/
# **********************************************************************
# %%
# Copyright (C) 2012 - 2019 Pi4J
# %%
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# #L%
###

cd $(dirname $(readlink -f $0))

# first optional argument can be a single Java source file or "clean"
filename=$1

# if the first argument is "clean", then only clean the *.class files from the directory
if [ "$filename" = "clean" ]; then
  echo "-------------------------------------------------------------------------"
  echo " CLEANING Pi4J EXAMPLES"
  echo "-------------------------------------------------------------------------"
  rm -f *.class
  echo ".. done .."
  exit 0
fi

# otherwise, continue with building the samples
echo "-------------------------------------------------------------------------"
echo " BUILDING Pi4J EXAMPLES"
echo "-------------------------------------------------------------------------"

# check for user provided filename argument
if [ -z $filename ]; then
  # COMPILE ALL THE EXAMPLE JAVA SOURCE FILES

  # get total number of .java example source files
  total=`ls -l *.java | grep -v ^l | wc -l`
  index=1

  # iterate over all *.java files
  for filename in *.java; do
    printf "[%02d of %02d] ... compiling : $filename\n" $index $total

	# compile each *.java file with Pi4J in the classpath
	javac -classpath .:classes:/opt/pi4j/lib/'*' -d . $filename

    # increment index counter
	index=$((index+1))
  done

  # reset filename for printed execution instructions below
  filename="BlinkGpioExample.java"
else
  # COMPILE SINGLE JAVA SOURCE FILE
  echo "[1 of 1] ... compiling : $filename"
  javac -classpath .:classes:/opt/pi4j/lib/'*' -d . $filename
fi

# THE FOLLOWING INSTRUCTIONS WILL EXECUTE ONE OF THE EXAMPLES
echo "-------------------------------------------------------------------------"
echo "The following command syntax can be used to execute the sample projects:"
echo "  sudo pi4j --run ${filename%.*} "
echo "   - or - "
echo "  sudo java -classpath .:classes:/opt/pi4j/lib/'*' ${filename%.*}"
echo "   - or - "
echo "  ./run ${filename%.*}"
echo "-------------------------------------------------------------------------"

